package com.itheima.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.domain.Employee;
import com.itheima.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author CSY
 * 2022/5/12    14:10
 */
@Slf4j
@Configuration
public class UserInterceptor implements HandlerInterceptor {

    private RedisTemplate<Object, Object> redisTemplate;

    public UserInterceptor() {

    }

    public UserInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("AuthorizationUser");
        if (StrUtil.isNotEmpty(token)) {
            Object o = redisTemplate.opsForValue().get(TokenConstant.USER_TOKEN_PREFIX + token);
            if (Objects.nonNull(o)) {
                UserDto userDto = JSON.parseObject((String) o, UserDto.class);
                if (Objects.nonNull(userDto)) {
                    Long id = userDto.getId();
                    TokenHolder.setCurrentId(String.valueOf(id));
                    log.info("用户已登录，id为{}", id);
                    return true;
                }
            }

        }
        log.info("用户未登录");
        log.info(request.getRequestURI());

        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;

    }
}
